package com.weisha.bledemo.fragments;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import android.R.bool;
import android.R.integer;
import android.content.Intent;
import android.nfc.FormatException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.weisha.bledemo.MainActivity;
import com.weisha.bledemo.R;
import com.weisha.bledemo.Utils;
import com.weisha.bledemo.application.App;


public class SpeedTestFragment extends Fragment implements
		OnCheckedChangeListener, OnClickListener {

	private static RadioGroup rf_readOptions;
	private static RadioGroup rf_memOptions;
	private static TextView rf_textCallback;
	private static TextView rf_datarateCallback;
	private static EditText ed_write;
	private static boolean rf_chosen = false;
	private static boolean rf_MemChosen = false;
	private static TextView rf_EditCharMulti;
	private static TextView rf_TextCharMulti;
	private static Button bt_send;
	private static Button bt_Auto;
	private static Button bt_clean;
	protected static ScrollView mScrollView;
	public static Handler mHandler;
	
	protected final static String JUDGE_KEY = "is_recevied";
	protected final static String move_KEY = "notmovedown";
	protected final static String DATA_KEY = "uartnfc_data2233";
	protected final static String DATA_LENKEY = "DATALEN123654";
	protected final static String modify_KEY = "s5625dd";//自定义显示
	protected final static String Clean_KEY = "cleanLCDs";
	protected final static String String_key = "sdfsdfsd3223";
	protected final static String String_key2 = "sdfsdfsd3222";
	protected final static String modify_BIAOQING = "s562565556";//自定义显示
   protected Utils mUtil = new Utils();

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Values per default
		rf_MemChosen = true;
		rf_chosen = true;
		
		setRetainInstance(true);
		//mScrollView = (ScrollView) findViewById(R.id.windows_scroll);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View layout = inflater.inflate(R.layout.fragment_speedtest, container,
				false);
		/*

		rf_ButtonSpeedtest = (Button) layout.findViewById(R.id.startSpeedtest);
		rf_ButtonSpeedtest.setOnClickListener(this);

		rf_readOptions = (RadioGroup) layout
				.findViewById(R.id.radioReadOptions);

		rf_memOptions = (RadioGroup) layout
				.findViewById(R.id.radioMemoryOptions);
		rf_memOptions.setOnCheckedChangeListener(this);

		rf_textCallback = (TextView) layout.findViewById(R.id.rf_textCallback);*/
		
		
		rf_datarateCallback = (TextView) layout.findViewById(R.id.rf_datarateCallback);
		
		mScrollView = (ScrollView) layout.findViewById(R.id.windows_scroll);
		
		rf_EditCharMulti = (TextView) layout.findViewById(R.id.editCharMultipl);
		rf_TextCharMulti = (TextView) layout.findViewById(R.id.textCharMultipl);

		rf_EditCharMulti.setText("0");
		
		ed_write = (EditText) layout.findViewById(R.id.data_write);
		
		
		ed_write.addTextChangedListener(watcher);
		
		bt_send = (Button) layout.findViewById(R.id.CleanButtonSend);
		bt_Auto = (Button) layout.findViewById(R.id.CleanButtonAuto);
		bt_clean = (Button) layout.findViewById(R.id.CleanButtonClean);
		
		bt_send.setOnClickListener(this);
		bt_Auto.setOnClickListener(this);
		bt_clean.setOnClickListener(this);
		
		return layout;
	}

	
private TextWatcher watcher = new TextWatcher() {
	    
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	        // TODO Auto-generated method stub
	        
	    }
	    
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	        // TODO Auto-generated method stub
	        
	    }
	    
	    @Override
	    public void afterTextChanged(Editable s) {
	        // TODO Auto-generated method stub
	    	// get EditText text
            String text = ed_write.getText().toString();
            rf_EditCharMulti.setText(String.valueOf(text.getBytes().length));
	    }

		

		
	};
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		/*
		if (checkedId == R.id.radioMemoryEeprom) 
		{
			rf_MemChosen = false;
			rf_readOptions.setVisibility(View.GONE);
			rf_EditCharMulti.setHint(R.string.Ndef_char_multipl);
			rf_TextCharMulti.setText(getActivity().getResources().getString(
					R.string.Block_multipl_eeprom));
			
			
			String textCharMulti = getrf_ndef_value_charmulti();

			// getting text multiplier
			int chMultiplier = 1;
			int chMultiLength = textCharMulti.length();
			if (chMultiLength == 0) {
				chMultiplier = 1;
			} else {
				chMultiplier = Integer.parseInt(textCharMulti);
			}

			rf_EditCharMulti.setText(Integer.toString(chMultiplier * 64));
			
			
			// rf_ndef_CharMulti.setText("");
		} else if (checkedId == R.id.radioMemorySram) {
			rf_MemChosen = true;
			rf_readOptions.setVisibility(View.VISIBLE);
			rf_EditCharMulti.setHint(R.string.Block_multipl);
			rf_TextCharMulti.setText(getActivity().getResources().getString(
					R.string.Block_multipl_sram));
			
			String textCharMulti = getrf_ndef_value_charmulti();

			// getting text multiplier
			int chMultiplier = 1;
			int chMultiLength = textCharMulti.length();
			if (chMultiLength == 0) {
				chMultiplier = 1;
			} else {
				chMultiplier = Integer.parseInt(textCharMulti);
			}

			rf_EditCharMulti.setText(Integer.toString(chMultiplier / 64));
		}
		*/
	}

	private void StartEEPROMSpeedTest() {
		if (MainActivity.demo.isReady() && MainActivity.demo.isConnected()) {
			MainActivity.demo.FinishAllTasks();
			try {
				MainActivity.demo.EEPROMSpeedtest();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void StartSRAMSpeedTest() {
		if (MainActivity.demo.isReady() && MainActivity.demo.isConnected()) 
		{
			MainActivity.demo.FinishAllTasks();
			try {
				MainActivity.demo.SRAMSpeedtest();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static String getrf_ndef_value_charmulti() {
		return rf_EditCharMulti.getText().toString();
	}

	public static Boolean isSRamEnabled() {
		return rf_MemChosen;
	}

	public static void setAnswer(String answer) {	
		
		Bundle bundle = new Bundle();
		bundle.putByteArray(DATA_KEY, answer.getBytes());
		bundle.putBoolean(JUDGE_KEY, false);
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);
		
		
	}

	public static boolean getChosen() {
		return rf_chosen;
	}

	public static String getReadOptions() {
		int id = rf_readOptions.getCheckedRadioButtonId();
		View radioButton = rf_readOptions.findViewById(id);
		int radioId = rf_readOptions.indexOfChild(radioButton);
		RadioButton btn = (RadioButton) rf_readOptions.getChildAt(radioId);
		return (String) btn.getText();
	}

	public static void setReadOptions(int i) {
		//rf_readOptions.check(i);
	}

	public static void setDatarateCallback(String datarate) {
		
		//rf_datarateCallback.setText(datarate);
			
			Bundle bundle = new Bundle();
			bundle.putByteArray(DATA_KEY, datarate.getBytes());
			bundle.putBoolean(JUDGE_KEY, false);
			Message msg = new Message();
			msg.setData(bundle);
			mHandler.sendMessage(msg);
	
		
		
		
	}
	
public static void Display_bytes(byte[] inbyte,int len) 
{
		
		//rf_datarateCallback.setText(datarate);
			
			Bundle bundle = new Bundle();
			bundle.putByteArray(DATA_KEY, inbyte);
			bundle.putBoolean(JUDGE_KEY, true);
			Message msg = new Message();
			msg.setData(bundle);
			mHandler.sendMessage(msg);
	
		
		
		
	}	
	
	
public static void DispClean() {
		
		//rf_datarateCallback.setText(datarate);
		rf_datarateCallback.setText("");
		ed_write.setText("");
	}

@Override
public void onStart() {
	// TODO Auto-generated method stub
	super.onStart();

	  rf_datarateCallback.setMovementMethod(new ScrollingMovementMethod());
	
	
		mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			displayData(rf_datarateCallback, msg);
		 	mScrollView.fullScroll(View.FOCUS_DOWN);
			super.handleMessage(msg); 
		}
	};
	
	
}

protected void displayData(TextView text, Message msg) {
	Bundle bundle = msg.getData();
	
	boolean sdf = bundle.getBoolean(Clean_KEY);
	if(sdf)
	{
		text.setText(" ");
	}
	else
	{
		byte[] data = bundle.getByteArray(DATA_KEY);
		
		boolean ifmodify =  bundle.getBoolean(modify_KEY);
		if(ifmodify)//自定义显示
		{
			String s=new String(data);
			text.append(s);
			text.append("\n");
			
			String sdfs=  bundle.getString(String_key);
			if(!sdfs.isEmpty())
			{
//				Toast.makeText(this, sdfs, 1000)
//				.show();
				/*
				Toast	toast = Toast.makeText(getApplicationContext(),
						sdfs, Toast.LENGTH_SHORT);
					   toast.setGravity(Gravity.CENTER, 0, 0);
					   LinearLayout toastView = (LinearLayout) toast.getView();
					   ImageView imageCodeProject = new ImageView(getApplicationContext());
					   imageCodeProject.setImageResource(R.drawable.smile);
					   toastView.addView(imageCodeProject, 0);
					   toast.show();
					   */
				
			}
			
		}else
		{
			boolean tagJudge = bundle.getBoolean(JUDGE_KEY);
			if (tagJudge)
			{
				text.append(mUtil.toHexString(data));
			}
			else
			{
				boolean flagmove = bundle.getBoolean(move_KEY);
				
				String s1=new String(data);
				
				if(flagmove)//在同一个地方显示
				{
					text.setText(s1);
				}
				else //往下移
				{
				  text.append(s1);
				 
				}
			}
			
			//text.append("SendData:");
			
			text.append("\n");
		}
		

	}
	
}		


public static void displaynomove(String datarate)
{
	//rf_datarateCallback.setText(datarate);
	Bundle bundle = new Bundle();
	bundle.putByteArray(DATA_KEY, datarate.getBytes());
	bundle.putBoolean(JUDGE_KEY, false);
	bundle.putBoolean(move_KEY,true );
	Message msg = new Message();
	msg.setData(bundle);
	mHandler.sendMessage(msg);	
	
}

	public static String getDatarateCallback() {
		return rf_datarateCallback.getText().toString();
	}
	/**
	 * byte[] 转为String
	 */
	public static String Bytes2HexString(byte[] b) { 
	    String ret = ""; 
	    for (int i = 0; i < b.length; i++) { 
	        String hex = Integer.toHexString(b[i] & 0xFF); 
	       
	        if (hex.length() == 1) { 
	            hex = '0' + hex; 
	        } 
	        ret += hex.toUpperCase(); 
	    } 
	    return ret; 
	} 
	
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.CleanButtonSend:
			//startActivity(new Intent(this, SerialPortPreferences.class));
//			SendDatatoUart();
			SendData();
			break;

		case R.id.CleanButtonAuto:
			byte[] tembuffer = new byte[4096];
			int icount=0;
			Boolean loops=true;
			
			
			while(loops)
			{
				for(int i=0x30;i<0x39;i++)
				{
					tembuffer[icount]=(byte)i;
					icount++;
					if(icount==4096)
					{
						
						loops =false;
						break;
						
					}
				}
				
			}
			String recString = null;
			try {
				 recString=new String(tembuffer ,"ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			ed_write.setText(recString);
			
		     break;		
		case R.id.CleanButtonClean:
			DispClean();
			 break;
			 
		default:
			StartSRAMSpeedTest();
			break;
		}
		

	}


	protected void SendData(){
		String wholePasswprd= App.password.replace(",","");
		Byte[] pass = Utils.str2byte(wholePasswprd);
		Byte[] verifyCode = new Byte[]{Utils.verifyCode(pass)};
		Byte[] passjiaver = Utils.bytesMerger(pass, verifyCode);
		Byte[] qianzui = new Byte[]{Byte.valueOf((byte)-86), Byte.valueOf((passjiaver.length + 1)+""), 1};
		Byte[] wholeStr = Utils.bytesMerger(qianzui, passjiaver);
		byte[] newWholeStr = new byte[wholeStr.length];
		for (int i = 0; i < wholeStr.length; i++){
			newWholeStr[i] = wholeStr[i];
		}
		Bundle bundle = new Bundle();
		bundle.putByteArray(DATA_KEY, newWholeStr);
		bundle.putInt(DATA_LENKEY, newWholeStr.length);
		Message msg = new Message();
		msg.setData(bundle);
		if(MainActivity.demo.mHandler1!=null) {
			MainActivity.demo.mHandler1.sendMessage(msg);
		}else{
			Toast.makeText(getActivity(), "请接触NFC设备后重试！", Toast.LENGTH_SHORT).show();
		}
	}

protected void SendDatatoUart()
{
	if (ed_write.getText().toString().equals("")) 
	{
		//Toast.makeText(this, "data is null!!", 1000).show();
		setDatarateCallback("data is null!!");
		 return;
	}
	
	CharSequence t = ed_write.getText();
	char[] text = new char[t.length()];
	for (int i = 0; i < t.length(); i++) 
	{
		text[i] = t.charAt(i);
	}
	byte[] sd = new String(text).getBytes();
	
//	MainActivity.demo.SendData_call(sd,t.length());
	
	Bundle bundle = new Bundle();
	bundle.putByteArray(DATA_KEY, sd);
	bundle.putInt(DATA_LENKEY, t.length());
	Message msg = new Message();
	msg.setData(bundle);
	if(MainActivity.demo.mHandler1!=null) {
		MainActivity.demo.mHandler1.sendMessage(msg);
	}else{
		Toast.makeText(getActivity(), "请接触NFC设备后重试！", Toast.LENGTH_SHORT).show();
	}
	
}	

}
